package jwt

import (
	"Junior_two/video/videoapi/internal/utils"
	"errors"
	"net/http"
	"strings"

	"Junior_two/video/videoapi/internal/logic/jwt"
	"Junior_two/video/videoapi/internal/svc"
	"Junior_two/video/videoapi/internal/types"
	"github.com/zeromicro/go-zero/rest/httpx"
)

func VideoHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {

		f, h, e := r.FormFile("content")
		if e != nil {
			httpx.ErrorCtx(r.Context(), w, e)
			return
		}
		if h.Size > 2*1024*1024 {
			httpx.ErrorCtx(r.Context(), w, errors.New("文件不能超过2m"))
			return
		}
		if strings.HasPrefix(h.Filename, "png") || strings.HasPrefix(h.Filename, "jpg") {
			httpx.ErrorCtx(r.Context(), w, errors.New("文件格式不正确"))
			return
		}

		path, err := utils.Upload(h)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}
		r.Form.Set("content", path)

		defer f.Close()

		var req types.Publishrequest
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		l := jwt.NewVideoLogic(r.Context(), svcCtx)
		resp, err := l.Video(&req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
	}
}
